<script lang="ts" setup>
import { ElDialog, UploadProps, UploadFile, ElMessage } from 'element-plus'
import { ref } from 'vue'

const validImageFormats = ['jpg', 'jpeg', 'png'] //允许的文件后缀
//选择文件格式校验//并限制上传数量
const checkImageFormat = (file: any) => {
  console.log('文件格式校验')
  console.log(file)
  // noUpload.value = true
  const fileFormat = file.name.split('.').pop().toLowerCase() // 获取文件格式
  if (!validImageFormats.includes(fileFormat)) {
    ElMessage({ type: 'error', message: '商品图片格式必须为 jpg/jpeg/png' })
    faceList.value = [] //删除格式不符合的文件
    return false // 阻止文件上传
  }

  noUpload.value = true //设置为true阻止继续上传
  return true // 允许文件上传
}

const dialogImageUrl = ref('') //预览图片路径
const dialogVisible = ref(false) //预览框可见
//删除
const handleRemove: UploadProps['onRemove'] = (file: UploadFile) => {
  console.log('删除图片：')
  console.log(faceList.value)
  noUpload.value = false
}
//预览
const handlePictureCardPreview: UploadProps['onPreview'] = (
  file: UploadFile,
) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}

const faceList = ref([]) //图片列表
const noUpload = ref(false) //不再上传
</script>

<template>
  <div>
    <el-upload
      :class="{ disabled: noUpload }"
      :auto-upload="false"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-change="checkImageFormat"
      :on-remove="handleRemove"
      :limit="1"
      ref="businessLicense"
      :file-list="faceList"
    >
      <el-icon v-if="faceList.length == 0">
        <Plus />
      </el-icon>
    </el-upload>

    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<style scoped>
::v-deep .disabled .el-upload--picture-card {
  display: none !important;
}
</style>
